package com.learn.practice.security;

import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.learn.practice.pojo.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

@Component
public class AdminAuthenticationTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {

        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token) || !token.startsWith("jwt_")){
            //如果不存在和前缀不是TokenHeader.ADMIN_TOKEN_PREFIX，就放行到下一个过滤器
            chain.doFilter(request, response);
            SecurityContextHolder.clearContext();
            return;
        }
        //获取真实的token(去掉前缀)
        String authToken = token.substring("jwt_".length());

        //解析token
        JWT jwt;
        String userName = null;
        try{
            jwt = JWTUtil.parseToken(authToken);
        }catch (Exception e){
            chain.doFilter(request, response);
            return;
        }
        if (!Objects.isNull(jwt.getPayload("uid"))) {
            userName = jwt.getPayload("uid").toString();
        }
        if (!StringUtils.hasLength(userName)){
            chain.doFilter(request, response);
            return;
        }

        //从缓存中获取用户信息
        if (!AdminAuthenticationSuccessHandler.jwtTokenCache.containsKey(userName)){
            chain.doFilter(request, response);
            return;
        }

        HashMap<String,Object> userMap = (HashMap<String, Object>) AdminAuthenticationSuccessHandler.jwtTokenCache.get(userName);
        if (Objects.isNull(userMap)){
            chain.doFilter(request, response);
            return;
        }

        //保存相关的验证信息
        LoginUser user = (LoginUser)userMap.get("userObject");
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        chain.doFilter(request, response);
    }
}